<template>
	<!-- <scroll-view scroll-y class="options-scroll"> -->
	<view class="setting-box">
		<view>
			<image src="/static/images/left.png" class="left-icon" @click="backToLast"></image>
		</view>
		<!-- 信息展示 -->
		<view class="top-box">
			<view>
				<image src="/static/images/logo.png" class="avatar-style" alt="avatar"></image>
				<view class="title-style">{{$t("PersonalInfo")}}</view>
			</view>
		</view>
		<!-- 面板-->
		<view style="height:100%;background-color: #fff;">

			<!-- 头像 -->
			<view class="list-row">
				<view style="width: 40%;">{{$t('avatar')}}</view>
				<view class="row-right" @click="editAvatar">
					<view style="margin-right: 0.3rem;">
						<u-avatar :src="userFullInfo.avatarUrl" class="avatar-style2" size="90rpx"
							alt="avatar"></u-avatar>
						<!-- <image :src="userFullInfo.avatarUrl" class="avatar-style2"></image> -->
					</view>
					<view>
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view>
			<!-- 用户名称 -->
			<view class="list-row">
				<view style="width: 40%;">{{$t('username')}}</view>
				<view class="row-right" @click="editName">
					<view class="list-right-word">
						<view class="omit-word">
							{{userFullInfo.username}}
						</view>
					</view>
					<view>
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view>
			<!-- 账户ID -->
			<view class="list-row">
				<view style="width: 40%;">{{$t('accountId')}}</view>
				<view class="row-right">
					<view class="list-right-word" style="margin-right: 1.5rem;" @longpress="copyText">
						{{userFullInfo.dplID}}
					</view>
				</view>
			</view>

			<!-- 手机号码 -->
			<view class="list-row">
				<view style="width: 38%">{{$t('phoneNumber')}}</view>
				<view class="row-right">
					<!-- 未绑定 -->
					<view v-if="!havePhone" class="list-right-word" @click="goBindPhone(userFullInfo.phone)">
						{{$t('unbound')}}
					</view>
					<!-- 已绑定 -->
					<view v-else class="list-right-word" @click="goBindPhone(userFullInfo.phone)">
						<view style="margin-right: 0.3rem;">
							{{userFullInfo.phone}}
						</view>
						<view>
							{{$t('haveBound')}}
						</view>
					</view>
					<view>
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view>
			<!-- 邮箱 -->
			<!-- <view class="list-row">
				<view>{{$t('email')}}</view>
				<view class="row-right">
					<view v-if="!haveEmail" class="list-right-word" @click="goBindEmail(userFullInfo.email)">
						{{$t('unbound')}}
					</view>
					<view v-else class="list-right-word" @click="goBindEmail(userFullInfo.email)">
						<view style="margin-right: 0.3rem;">
							{{userFullInfo.email}}
						</view>
						<view>
							{{$t('haveBound')}}
						</view>
					</view>
					<view>
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view> -->

			<!-- 微信 -->
			<view class="list-row">
				<view style="width: 40%;">{{$t('wechat')}}</view>
				<view class="row-right">
					<view v-if="!haveweChat" class="list-right-word" @click="goBindWeChat()">
						{{$t('unbound')}}
					</view>
					<view v-else class="list-right-word" @click="UnbindWeChat()">
						{{$t('haveBound')}}
					</view>
					<view>
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view>

			<!-- 注销账号-->
			<view class="list-row">
				<view style="width: 40%;">{{$t('logoutAccount')}}</view>
				<view class="row-right">
					<view @click="goLogout()">
						<image src="/static/images/right.png" class="arrow-style"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 修改名称弹窗 -->
		<view class="popup-container" v-if="isEditName" :style="popUpStyle">
			<view class="popup-content">
				<view>
					<image src="/static/images/left.png" class="left-icon2" @click="editName"></image>
				</view>
				<view style="text-align: center;">
					<image src="/static/images/logo.png" class="popup-image"></image>
					<view style="margin-bottom: 0.8rem;">{{$t('editName')}}</view>
					<!-- @input="validateField" -->
					<input type="text" v-model="inputValue" @blur="validateField" @keyboardheightchange="onFocus"
						:class="{'error': !isValid}" :placeholder="$t('editNamePlaseholder')" class="popup-input" />
					<!-- 错误提示信息 -->
					<span v-if="showError" class="error-message">{{errorMessage}}</span>
					<u-button :loading="btnLoding" :loadingText="$t('confirm')" throttleTime='1000' class="popup-button"
						@click="confirmEdit">
						{{$t("confirm")}}
					</u-button>
					<!-- <button class="popup-button" @click="confirmEdit">{{$t("confirm")}}</button> -->
				</view>
			</view>
		</view>

		<!-- 修改头像 -->
		<view>
			<up-popup :show="isEditAvatar" mode="bottom" :round="5" @close="close" @open="editAvatar" closeable>
				<view class="edit-avatar-box">
					<view class="box-header">
						<view class="line"></view>
						<view class="avatar-setting-title">{{$t('avatarSetting')}}</view>
						<view class="line2"></view>
					</view>
					<view class="box-contain">
						<!-- 头像九宫格 -->
						<view class="avatar-list">
							<view class="avatar-box" v-for="(item,index) in avatarList" :key="index"
								@click="selectavatar(index)" :class="{ 'selected-avatar': selectedIndex === index }">
								<view class="avatar-border">
									<!-- 选中时的图标 -->
									<view class="icon-select-box" v-if="selectedIndex === index">
										<image src="/static/images/select.png" class="icon-select"></image>
									</view>
									<image :src="item.signUrl" class="avatar-img"></image>
								</view>
							</view>
						</view>
						<!-- 按钮 -->
						<view class="popup-button" style="margin: 2.5rem auto 1rem;"
							@click="changeAvatar(selectedIndex)">{{$t('confirm')}}</view>
					</view>
				</view>
			</up-popup>
		</view>

		<!-- 解绑微信弹窗 -->
		<view v-if="isUnbindWechat" class="popup-container">
			<view class="unbindWechat-box">
				<view style="text-align: center;">
					<image src="/static/images/logo.png" class="popup-image2"></image>
				</view>
				<view class="tip-contain">
					{{$t('unbindWeChatTip')}}
				</view>
				<!-- <view class="line-divider"></view> -->
				<view class="option-style">
					<button class="cancle-style" @click="UnbindWeChat">{{$t('cancel')}}</button>
					<button class="confirm-style" @click="goUnbind">{{$t('confirm')}}</button>
				</view>
			</view>
		</view>
	</view>
	<!-- </scroll-view> -->
	<upModal :modalWidth="'15rem'" :modalShow="modalShow" :modalText1="modalText1" :showImage="true" :isCancel="false"
		:isAgreement="false" :isAgreement2="false" @cancel="cancel" @cloos="cloos">
	</upModal>
</template>

<script setup lang="ts">
	import { computed, ref } from 'vue'
	import { useI18n } from 'vue-i18n'
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import { getFull } from "@/api/meApi/me.js"
	import { setUserName, getAvatarList, setAvatar, bindWx, unbindWx } from "@/api/setting/setting.js"
	import upModal from '../../components/upModal.vue'
	onShow(() => {
		getUserData()
	})
	interface FullInfo {
		avatarUrl : string,
		dplID : string,
		username : string,
		phone ?: string,
		email ?: string,
		wxcode ?: string
	}

	const userFullInfo = ref<FullInfo>({
		avatarUrl: '',
		dplID: '',
		username: '',
		phone: '',
		email: '',
		wxcode: ''
	})
	const havePhone = ref<Boolean>(false)
	const haveEmail = ref<Boolean>(false)
	const haveweChat = ref<Boolean>(false)
	function getUserData() {
		getFull().then(res => {
			console.log('获取用户信息 settingInfo full', res);
			if (res.code == 200 && res.msg == 'success') {
				userFullInfo.value = res.data
				inputValue.value = userFullInfo.value.username
			}
			if (userFullInfo.value.phone != '') {
				havePhone.value = true
			}
			if (userFullInfo.value.email != '') {
				haveEmail.value = true
			}
			if (userFullInfo.value.wxcode != '') {
				haveweChat.value = true
			}
		})
	}
	// 是否显示修改名字弹窗
	const isEditName = ref<Boolean>(false)

	const inputValue = ref<String>('');
	const isValid = ref<Boolean>(true)
	const showError = ref(false)
	const { t } = useI18n()
	const errorMessage = ref('')
	const btnLoding = ref(false) //修改名字弹窗按钮的加载
	// 是否显示修改头像弹窗
	const isEditAvatar = ref<Boolean>(false)
	interface AvatarType {
		avatarUrl : string;
		signUrl : string
	}
	const selectedIndex = ref(-1) // 初始未选中任何头像
	// 选中的头像地址
	const selectAvatar = ref<String>("")
	// 头像列表
	const avatarList = ref<AvatarType[]>([])
	const popStyle = ref(false)  //修改用户名弹框 是否上移
	// 定义样式对象，明确指定类型
	const popUpStyle = computed(() => ({
		'margin-top': popStyle.value ? '-10rem' : '0rem', // 明确使用rem单位
	}));
	// 是否显示解绑微信弹窗
	const isUnbindWechat = ref<Boolean>(false)

	// 微信openID
	const openId = ref<String>('')

	const modalShow = ref(false) // 弹窗显示状态
	const modalText1 = ref('') // 弹窗内容
	const cancel = () => {
		modalShow.value = false
	}
	const cloos = () => {
		if (modalText1.value == t('bindPhone')) {
			goBindPhone('')
		}
		modalShow.value = false
	}

	const backToLast = () => {
		uni.navigateBack()
	}
	function goSettinfInfo() {
		uni.navigateTo({
			url: '/pages/setting/settingInfo'
		})
	}
	// 编辑用户名
	function editName() {
		isEditName.value = !isEditName.value
		inputValue.value = userFullInfo.value.username
	}

	function confirmEdit() {
		validateField();
		if (!isValid.value) {
			return; // 如果无效则阻止进一步操作
		}
		btnLoding.value = true
		if (inputValue.value === userFullInfo.value.username) {
			uni.showToast({
				title: t('editNamePlaseholder'), //请输入新的用户名
				icon: 'none',
				duration: 1000
			})
			btnLoding.value = false
		} else {
			setUserName({ username: inputValue.value }).then((res) => {
				if (res.code == 200 && res.msg == 'success') {
					isEditName.value = false
					modalShow.value = true
					modalText1.value = t('editNameSuccess')
					getUserData()
				} else {
					// uni.showToast({
					// 	title: res.msg,
					// 	icon: 'none',
					// 	duration: 1500
					// })
					modalShow.value = true
					if (res.msg == '用户名长度不能超过30个字符') {
						modalText1.value = t('nameLengthError2')
					} else if (res.code == 13121205) {  //违规
						modalText1.value = t('nameViolation')
					} else {
						modalText1.value = res.msg
					}
					inputValue.value = ''
				}
			}).catch(() => { }).finally(() => {
				btnLoding.value = false
			})
		}
	}
	// 当输入框聚焦时触发的函数 调整样式 输入框弹出键盘时，修改用户名弹框自动向上移动
	function onFocus() {
		popStyle.value = true
	}

	// 计算字符串的 UTF-8 字节长度（兼容旧版 Android）
	const getUTF8ByteLength = (str) => {
		let byteLength = 0;
		for (let i = 0; i < str.length; i++) {
			const charCode = str.charCodeAt(i);
			if (charCode <= 0x7F) {
				// 单字节字符（ASCII）
				byteLength += 1;
			} else if (charCode <= 0x7FF) {
				// 双字节字符
				byteLength += 2;
			} else if (charCode <= 0xFFFF) {
				// 三字节字符
				byteLength += 3;
			} else {
				// 四字节字符（Unicode 代理对）
				byteLength += 4;
				i++; // 跳过代理对的第二个字符
			}
		}
		return byteLength;
	};

	// 当输入框失去焦点时触发的函数
	// 验证函数
	const validateField = () => {
		const value = inputValue.value.trim()
		popStyle.value = false
		// 检查是否为空
		if (!value) {
			isValid.value = false
			errorMessage.value = t('nameRequired') // 请输入用户名
			showError.value = true
			return
		}
		// 检查长度是否在2-16个字之间
		// if (value.length < 2 || value.length > 16) {
		// 	isValid.value = false
		// 	errorMessage.value = t('nameLengthError') // 用户名长度必须在2-16个字之间
		// 	showError.value = true
		// 	return
		// }
		// 使用替代方法计算字节长度
		let num = getUTF8ByteLength(value);
		// 计算字符串在UTF-8编码下的字节数
		// let num = new TextEncoder().encode(value).length
		// 检查长度是否在2-16个字之间  0718改为1字符-10个字
		if (num < 1 || num > 30) {
			isValid.value = false
			errorMessage.value = t('nameLengthError') // 用户名长度必须在6-48个字节之间  1-30字节
			showError.value = true
			return
		}
		// 验证通过
		isValid.value = true
		showError.value = false
	}
	// 编辑头像 
	function editAvatar() {
		isEditAvatar.value = true;
		getAvatarList().then((res) => {
			if (res.code == 200) {
				avatarList.value = res.data
			}
		})
	}

	function close() {
		isEditAvatar.value = false;
	}
	// 选择头像
	function selectavatar(index : number) {
		selectedIndex.value = index
	}
	// 点击ok按钮 更改头像
	function changeAvatar(index : number) {
		selectAvatar.value = avatarList.value[index].avatarUrl
		setAvatar({ avatarUrl: selectAvatar.value }).then((res) => {
			isEditAvatar.value = false;
			if (res.code == 200) {
				getUserData()
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 1500
				})
			}
		})
	}

	// 绑定手机号
	function goBindPhone(phone : string) {
		uni.navigateTo({
			url: `/pages/setting/bindPhone?phone=${phone}` // 使用反引号
		})
	}
	// 绑定邮箱号
	function goBindEmail(email : string) {
		uni.navigateTo({
			url: `/pages/setting/bindPhone?email=${email}` // 使用反引号
		})
	}

	// 是否显示解绑微信弹窗 
	const UnbindWeChat = () => {
		isUnbindWechat.value = !isUnbindWechat.value
	}

	//绑定微信
	const goBindWeChat = () => {
		// todo 绑定微信操作
		uni.login({
			"provider": "weixin",
			"onlyAuthorize": true, // 微信登录仅请求授权认证
			success: function (event) {
				console.log('获取event:', event);
				// const { code } = event
				//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
				bindWx({ wxcode: event.code }).then((res) => {
					console.error('接口结果:', res);
					if (res && res.code == 200) {
						openId.value = res.OpenId
						console.error('获取OpenId:', res.OpenId);
						// haveweChat.value = true
						getUserData()
					} else {
						// uni.showToast({
						// 	title: res.msg,
						// 	icon: "none"
						// })
						modalShow.value = true
						if (res.code == 11112) { //微信已经注册过或者绑定
							modalText1.value = t('wxBound')
						} else {
							modalText1.value = res.msg
						}
						console.log("1111111", res)
					}
				})
			},
			fail: function (err) {
				//登录授权失败
				console.error('获取code失败:', err);
				uni.showToast({
					title: err,
					icon: "none"
				})
				// modalShow.value = true
				// modalText1.value= err
			}
		})
	}
	// 解绑微信 
	const goUnbind = () => {
		// 关闭弹窗
		UnbindWeChat()
		if (userFullInfo.value.phone == '') {
			// 未绑定手机号 去绑定
			// uni.showToast({
			// 	title: t('bindPhone'),
			// 	icon: "none"
			// })
			modalShow.value = true
			modalText1.value = t('bindPhone')
		}
		else {
			// todo 解绑微信操作
			unbindWx().then((res) => {
				console.log('解绑微信:', res);
				if (res && res.code == 200) {
					// 解绑成功
					uni.showToast({
						title: t('unbindSuccess'),
						icon: "none"
					})
					// 显示未绑定
					haveweChat.value = false
				} else {
					if (res.code == 11114) {  //用户没有绑定微信
						modalShow.value = true
						modalText1.value = t('notBoundWeChat')
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
							duration: 1000
						})
					}
				}
			})
		}
	}
	// 跳转到注销页
	function goLogout() {
		uni.navigateTo({
			url: '/pages/setting/logoff'
		})
	}

	// 长按复制
	function copyText() {
		const textToCopy = userFullInfo.value.dplID;
		uni.setClipboardData({
			data: textToCopy,
			success: () => {
				uni.showToast({
					title: '复制成功',
					icon: 'none'
				});
			}
		});
	}
</script>

<style lang="scss" scoped>
	.setting-box {
		width: 100%;
		height: 100%;
		/*微信小程序无法使用本地资源图片作为背景图 使用base64格式*/
		background-image: url('');
		background-size: cover;
		background-repeat: no-repeat;
		box-sizing: border-box;
		padding: 2rem 0;
		/* #ifdef  MP-WEIXIN*/
		padding-top: 3.5rem;
		/* #endif*/
	}

	.left-icon {
		width: 1.5rem;
		height: 1.5rem;
		margin: 0rem 0 0 0.5rem;
		/* #ifdef  MP-WEIXIN*/
		margin: 0rem 0 0 0.5rem;
		/* #endif*/
	}

	.top-box {
		width: 100%;
		height: 11rem;
		background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
		position: relative;
		text-align: center;
	}

	.avatar-style {
		width: 8.38rem;
		height: 8.38rem;
		border-radius: 50%;
	}

	.title-style {
		height: 1.5rem;
		line-height: 1.5rem;
		color: rgba(16, 16, 16, 0.8);
		font-size: 0.88rem;
		font-weight: 600;
		text-align: center;
		margin-bottom: 1rem;
	}

	.name-style {
		height: 1.88rem;
		line-height: 1.88rem;
		margin-bottom: 0.5rem;
	}

	.icon-style {
		width: 1.5rem;
		height: 1.5rem;
	}

	.list-row {
		width: 100%;
		height: 3.72rem;
		line-height: 3.72rem;
		color: rgb(28, 34, 42);
		background-color: #fff;
		font-size: 1rem;
		border-bottom: 0.1rem solid rgba(247, 247, 247, 1.0);
		padding: 0 0.8rem;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.omit-word {
		display: block;
		height: 3.72rem;
		line-height: 3.72rem;
		width: 100%;
		text-align: right;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		/* 简化为单行截断 */
	}

	.list-right-word {
		width: 85%;
		color: rgb(153, 153, 153);
		margin-right: 0.3rem;
		display: flex;
		justify-content: flex-end;
	}

	.avatar-style2 {
		margin: 0.42rem 0;
		width: 2.85rem;
		height: 2.88rem;
		border-radius: 3.13rem;
	}

	.row-right {
		width: 70%;
		display: flex;
		justify-content: flex-end;
	}

	.arrow-style {
		width: 1.2rem;
		height: 1.22rem;
		margin: 1.25rem 0;
	}

	.popup-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .5);
		display: flex;
		justify-content: center;
		align-items: center;
		// margin-top: -10rem;
	}

	.popup-content {
		width: 70%;
		background-color: white;
		padding: 20px;
		border-radius: 10px;
		box-sizing: border-box;
	}

	.left-icon2 {
		width: 1.5rem;
		height: 1.5rem;
		margin: -3rem 0 0 -1rem;
	}

	.popup-image {
		width: 6.5rem;
		height: 6.5rem;
		border-radius: 50%;
	}

	.popup-input {
		margin: 0 auto;
		text-align: left;
		padding-left: 0.5rem;
		font-size: 0.88rem;
		border-radius: 5px;
		width: 12.5rem;
		height: 1.88rem;
		color: rgba(136, 136, 136, 1);
		border: 0.06rem solid rgba(187, 187, 187, 1);
	}

	/* 输入框错误样式 */
	.error {
		border-color: red;
	}

	/* 错误提示信息样式 */
	.error-message {
		color: red;
		font-size: 12px;
	}

	.popup-button {
		width: 6.13rem;
		height: 2rem;
		line-height: 2rem;
		border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
		background-color: rgba(222, 134, 143, 1);
		color: rgba(255, 255, 255, 1);
		font-size: 0.88rem;
		text-align: center;
		margin-top: 1rem;
		border: none;
	}

	.edit-avatar-box {
		width: 100%;
		text-align: center;
	}

	.box-header {
		padding: 1rem 0;
	}

	.box-contain {
		padding: 1rem 0.8rem;
		box-sizing: border-box;
		// height: 30rem;
	}

	.line {
		width: 3.94rem;
		height: 0.26rem;
		background-color: rgba(187, 187, 187, 1);
		margin: 0 auto;
	}

	.avatar-setting-title {
		height: 2.5rem;
		line-height: 2.5rem;
		color: rgba(16, 16, 16, 1);
		font-size: 1.25rem;
		font-weight: 600;
		margin: 0 auto;
	}

	.line2 {
		width: 100%;
		height: 0.08rem;
		background-color: rgba(218, 218, 218, 1.0);
	}

	.avatar-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.avatar-box {
		flex: 0 0 calc((100% - 0.4rem)/3);
		margin-bottom: 0.4rem;

	}

	.avatar-border {
		border: 2px solid #eee;
		border-radius: 50%;
		width: 6.55rem;
		height: 6.45rem;
		position: relative;
	}

	/* 选中状态的样式 */
	.selected-avatar .avatar-border {
		border-color: #000;
		/* 选中时边框变黑 */
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
		/* 添加阴影效果 */
		transition: all 0.3s ease;
		/* 添加过渡动画 */
	}

	.icon-select-box {
		position: absolute;
		left: 85%;
	}

	.icon-select {
		width: 1.25rem;
		height: 1.25rem;
	}

	.avatar-img {
		width: 6.25rem;
		height: 6.25rem;
		border-radius: 50%;
		margin-top: 0.075rem;
		margin-left: 0.04rem;
	}

	.unbindWechat-box {
		width: 68%;
		background-color: white;
		padding: 20px 20px 15px 20px;
		border-radius: 0.5rem;
		box-sizing: border-box;
		height: auto;
	}

	.popup-image2 {
		width: 240rpx;
		height: 236rpx;
		border-radius: 50%;
	}

	.tip-contain {
		margin: 0 auto;
		width: 90%;
		/* height: 2.5rem;*/
		line-height: 1.25rem;
		color: rgba(16, 16, 16, 1);
		font-size: 0.92rem;
		/**/
		font-weight: 600;
		text-align: center;
	}

	.line-divider {
		margin-top: 0.5rem;
		width: 100%;
		border-bottom: 0.04rem solid rgba(232, 232, 232, 1.0);
	}

	.option-style {
		display: flex;
		justify-content: space-between;
		margin-top: 1rem;
	}

	.cancle-style {
		width: 40%;
		height: 2rem;
		line-height: 2rem;
		border-radius: 0.6rem;
		color: #fff;
		background-color: #adadad;
		font-size: 0.88rem;
		text-align: center;
		border: none;
	}

	.confirm-style {
		width: 40%;
		height: 2rem;
		line-height: 2rem;
		border-radius: 0.6rem;
		background-color: rgba(222, 134, 143, 1);
		color: rgba(255, 255, 255, 1);
		font-size: 0.88rem;
		text-align: center;
		border: none;
	}

	.options-scroll {
		height: 100%;
	}
</style>